package com.bigflexlib.x.XML
{
	import com.adobe.net.URI;
	
	
	public class XMLUtil
	{
		
		
		
		public static function firstChildValueAsString( parentNode:XML, childNodeName:String, defaultValue:String = null ):String
		{
			if ( parentNode.elements( childNodeName ).length() == 0 )
				return defaultValue;
			return  parentNode.elements( childNodeName )[ 0 ].toString();
		}
		
		
		
		public static function firstChildValueAsNumber( parentNode:XML, childNodeName:String, defaultValue:Number = 0 ):Number
		{
			var valueAsString:String = firstChildValueAsString( parentNode, childNodeName );
			if ( valueAsString == null )
				return defaultValue;

			return Number( valueAsString ); // what happens if this fails??

		}
		
		

		/**
		 * 
		 * 
		 * 
		 * @param uriString
		 * @param enclosingXMLNode
		 * @param fallbackBaseURI
		 * @return 
		 * 
		 */
		public static function fullyQualifyURIWithinXMLNode( uriString:String, enclosingXMLNode:XML, fallbackBaseURI:String = null  ):String
		{	
			// rdf:about, rdf:resource, rdf:ID and rdf:datatype.
			
			var uri:URI = new URI( uriString ); // it is already fully qualified
			if ( uri.isAbsolute() )
				return uri.toString();

			var baseURI:String = XMLUtil.getXMLBaseForNode( enclosingXMLNode );
			
			if ( baseURI == null )
				baseURI = fallbackBaseURI;

			if ( baseURI == null ) // we were unable to fully qualify the URI
				return null;
			
			if ( ! uri.makeAbsoluteURI( new URI( baseURI ) ) )
				return null;
			
			return uri.toString();	
			
		}		
		
		
		public static function getTopNode( node:XML ):XML
		{
			var p:XML = ( node.parent( ) as XML );
			if ( p ==  null )
				return node;
			return getTopNode( p );
		}
		
		
		public static function removeNodeFromParent( node:XML ):void
		{
			try{
				delete node.parent( ).*[ node.childIndex( ) ];
			}catch(e:Error){}
		
		
		}
		
		
		/**
		 * 
		 * traverses up the hierarchy of nodes until an xml:base declaration is found.
		 * if none is found, returns null
		 * 
		 * @param xmlNode
		 * @return 
		 * 
		 */		
		public static function getXMLBaseForNode( xmlNode:XML ):String
		{
			var xmlNS:Namespace = new Namespace( "xml", "http://www.w3.org/XML/1998/namespace" );
			
			if ( xmlNode.@xmlNS::base.length() > 0 )
				return xmlNode.@xmlNS::base.toString();
				
			if ( xmlNode.parent() == null )
				return null;
				
			return getXMLBaseForNode( xmlNode.parent() );
		}
		
		
		/**
		 * 
		 * @param node
		 * @return 
		 * 
		 */		
		public static function getXMLNodeURI( node:XML ):String
		{
			return node.name().toString().replace("::","");
		}					
				
		
	}

}